import React, { useRef, useState, useEffect } from 'react'
import { PageContainer } from '@ant-design/pro-layout'
import { PlusOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Avatar, Switch, message } from 'antd';
import ProTable from '@ant-design/pro-table';
import { getUsers, lockUser, addUser } from '@/services/userList'
import { set } from 'lodash';
import CreateOrEdit from './components/CreateOrEdit';

const User = () => {
  //表格的ref，便于自定义操作表格
  const actionRef = useRef()
  //将表单初始化的值设置为状态，在编辑的时候，使用这个状态
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editId,setEditId]=useState(undefined)
  //是否禁用用户
  const lockUserFun = async (uid) => {
    const res = await lockUser(uid)
    if (res.status === undefined) {
      message.success('操作成功')
    } else {
      message.error('操作失败')
    }
  }
  //控制模态框显示和隐藏
  const isShowModal = (show,id=undefined) => {
    setEditId(id)
    setIsModalVisible(show)
  }

  const columns = [
    {
      title: '头像',
      dataIndex: 'avatar_url',
      hideInSearch: true,
      render: (_, record) => <Avatar size={64} icon={<UserOutlined />} src={record.avatar_url} />
    }, {
      title: '姓名',
      dataIndex: 'name'
    }, {
      title: '邮箱',
      dataIndex: 'email'
    }, {
      title: '是否禁用',
      dataIndex: 'is_locked',
      hideInSearch: true,
      render: (_, record) => <Switch checkedChildren="开启" unCheckedChildren="关闭"
        defaultChecked={record.is_locked === 0} onChange={() => lockUserFun(record.id)} />
    }, {
      title: '创建时间',
      dataIndex: 'created_at',
      hideInSearch: true
    }, {
      title: '操作',
      render: (_, record) => <a onClick={() =>isShowModal(true,record.id)}>编辑</a>,
      hideInSearch: true
    }
  ]
  //获取用户列表
  const getData = async (params) => {
    const res = await getUsers(params)
    return {
      data: res.data,
      success: true,
      total: res.meta.pagination.total
    }
  }
  return (
    <PageContainer>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => getData(params)}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="用户列表"
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined />} type="primary"
            onClick={() => isShowModal(true)} >
            新建
          </Button>,
        ]}
      />
      {
        //模态框隐藏的时候，不挂载组件，模态框显示时候再挂载组件，这样是为了触发子组件的生命周期
        !isModalVisible ? '' :
          <CreateOrEdit isModalVisible={isModalVisible}
            isShowModal={isShowModal} actionRef={actionRef} editId={editId}/>
      }

    </PageContainer>
  )
}

export default User
